package com.rong.mbt.personal.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.calanger.hh.entity.ResultView;
import com.calanger.hh.model.Account;
import com.calanger.hh.model.CustomerService;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.R2;
import com.rong.mbt.personal.activity.AccountDetailOnDoctorActivity;
import com.rong.mbt.personal.activity.ArticleListOnDoctorActivity;
import com.rong.mbt.personal.activity.DoctorInfomationActivity;
import com.rong.mbt.personal.activity.DoctorPersonMainPageActivity;
import com.rong.mbt.personal.activity.MonkeyPackageActivity;
import com.rong.mbt.personal.activity.MyCommunityActivity;
import com.rong.mbt.personal.activity.MyQRcodeActivity;
import com.rong.mbt.personal.activity.PatientListOnDoctorActivity;
import com.rong.mbt.personal.activity.PersonalInfoActivity;
import com.rong.mbt.personal.activity.SettingActivity;
import com.rong.mbt.personal.activity.doctor.MyOrderActivity;
import com.rong.mbt.personal.bean.PersonalInfoBean;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.ImageUtil;
import com.rong.mbt.personal.utils.SpUtils;
import com.shehuan.niv.NiceImageView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.rong.imkit.RongIM;

/**
 * 医生模式-个人中心
 */

public class DoctorPersonalFragment extends Fragment {

    //    4.在lib中是使用ButterKnife ，手动把@bind中的R改成R2，这时候会报红，我们进行rebuild即 可。
    @BindView(R2.id.head_blue_iv_left)
    ImageView headBlueIvLeft;
    @BindView(R2.id.head_blue_tv_center)
    TextView headBlueTvCenter;
    @BindView(R2.id.head_blue_iv_right)
    ImageView headBlueIvRight;
    @BindView(R2.id.head_blue_tv_right)
    TextView headBlueTvRight;
    @BindView(R2.id.pf_np_iv_head)
    NiceImageView pfNpIvHead;
    @BindView(R2.id.tv_doctor_person_main_page)
    TextView tvDoctorPersonMainPage;
    @BindView(R2.id.pf_np_tv_name)
    TextView pfNpTvName;
    @BindView(R2.id.pf_np_tv_username)
    TextView pfNpTvUsername;
    @BindView(R2.id.pf_np_iv_jiantou)
    ImageView pfNpIvJiantou;
    @BindView(R2.id.tv_account_money)
    TextView tvAccountMoney;
    @BindView(R2.id.ll_account_num)
    LinearLayout llAccountNum;
    @BindView(R2.id.ll_patient_num)
    LinearLayout llPatientNum;
    @BindView(R2.id.ll_article_num)
    LinearLayout llArticleNum;
    @BindView(R2.id.fnp_head_relative)
    RelativeLayout fnpHeadRelative;
    @BindView(R2.id.fnp_monkey_pack_linear)
    LinearLayout fnpMonkeyPackLinear;
    @BindView(R2.id.fnp_shequ_linear)
    LinearLayout fnpShequLinear;
    @BindView(R2.id.ll_my_machine)
    LinearLayout llMyMachine;
    @BindView(R2.id.ll_black_box)
    LinearLayout llBlackBox;
    @BindView(R2.id.ll_personal_information)
    LinearLayout llPersonalInformation;
    @BindView(R2.id.ll_my_order)
    LinearLayout llMyOrder;
    @BindView(R2.id.fnp_monkey_pack_tv_invitation)
    TextView fnpMonkeyPackTvInvitation;
    @BindView(R2.id.fnp_nvitation_linear)
    LinearLayout fnpNvitationLinear;
    @BindView(R2.id.fnp_linear_share)
    LinearLayout fnpLinearShare;
    @BindView(R2.id.ll_customer_service)
    LinearLayout llCustomerService;
    @BindView(R2.id.fnp_setting_linear)
    LinearLayout fnpSettingLinear;
    @BindView(R2.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R2.id.tv_article_num)
    TextView tvArticleNum;
    @BindView(R2.id.ll_doctor_information)
    LinearLayout llDoctorInformation;
    private Unbinder unbinder;

    private String mbtToken;
    private PersonalInfoBean infoBean;
    private NiceImageView ivHead;
    private TextView tvName;
    private TextView tvPhone;
    private TextView tvInvitaion;
    private SharedPreferences sp;

    private int doctorId;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_doctor_personal, container, false);
        unbinder = ButterKnife.bind(this, view);
        doctorId = SpUtils.getDoctorId(getActivity());
        initView(view);
        listener(view);
        return view;
    }

    @OnClick(R2.id.tv_doctor_person_main_page)
    public void toDoctorPersonMainPage() {
        Intent intent = new Intent(getActivity(), DoctorPersonMainPageActivity.class);
        intent.putExtra("doctorId", doctorId);
        startActivity(intent);
    }

    @OnClick(R2.id.ll_doctor_information)
    public void toDoctorInformation() {
        Intent intent = new Intent(getActivity(), DoctorInfomationActivity.class);
        intent.putExtra("doctorId", doctorId);
        startActivity(intent);
    }

    private void listener(View view) {

        llCustomerService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkGo.<ResultView>get(UrlApi.customerServiceGetSingle)
                        .tag(this)
                        .headers("mbtToken", mbtToken)
                        .execute(new JsonCallback<ResultView>() {
                            @Override
                            public void onSuccess(Response<ResultView> response) {
                                ResultView resultView = response.body();
                                if (resultView.getData() != null) {
                                    Map<String, Object> map = (Map<String, Object>) resultView.getData();
                                    JSONObject jo = new JSONObject(map);
                                    CustomerService customerService = jo.getObject("customerService", CustomerService.class);
                                    RongIM.getInstance().startPrivateChat(getActivity(), customerService.getObjId() + "", "客服");

                                }
                            }

                            @Override
                            public void onError(Response<ResultView> response) {
                                super.onError(response);
                                Log.i("test", "onError  " + response.body());
                            }
                        });
            }
        });


        llAccountNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (infoBean == null || infoBean.getData() == null) {
                    return;
                }
                Intent intent = new Intent(getActivity(), AccountDetailOnDoctorActivity.class);
                intent.putExtra("infoBean", infoBean);
                intent.putExtra("doctorId", doctorId);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);
            }
        });

        llPatientNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), PatientListOnDoctorActivity.class);
                startActivity(intent);
            }
        });


        llArticleNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ArticleListOnDoctorActivity.class);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);
            }
        });


        //二维码
        view.findViewById(R.id.fnp_head_relative).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (infoBean == null || infoBean.getData() == null) {
                    return;
                }
                Intent intent = new Intent(getActivity(), MyQRcodeActivity.class);
                intent.putExtra("infoBean", infoBean);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);
            }
        });

        //设置
        view.findViewById(R.id.fnp_setting_linear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
            }
        });

        //个人信息
        view.findViewById(R.id.ll_personal_information).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), PersonalInfoActivity.class);
                if (infoBean != null) {
                    intent.putExtra("infoBean", infoBean);
                    intent.putExtra("mbtToken", mbtToken);
                }
                startActivity(intent);
            }
        });

        //我的订单
        view.findViewById(R.id.ll_my_order).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MyOrderActivity.class));
            }
        });


        //钱包
        view.findViewById(R.id.fnp_monkey_pack_linear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MonkeyPackageActivity.class);
                if (infoBean != null) {
                    intent.putExtra("phone", infoBean.getData().getPhone());
                    intent.putExtra("mbtToken", mbtToken);
                    intent.putExtra("name", infoBean.getData().getName());
                }
                startActivity(intent);
            }
        });
        //好友邀请
        view.findViewById(R.id.fnp_nvitation_linear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (infoBean != null && infoBean.getData() != null && infoBean.getData().getBelongcode() != null) {
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);

                    cm.setText(infoBean.getData().getBelongcode());
                    Toast.makeText(getActivity(), "复制成功，赶紧邀请好友注册吧", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "复制失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //我的矿机
        view.findViewById(R.id.ll_my_machine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/acitvity/MachineListActivity").navigation();
            }
        });

        //社区
        view.findViewById(R.id.fnp_shequ_linear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyCommunityActivity.class);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);

            }
        });

        //好友分享
        view.findViewById(R.id.fnp_linear_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ARouter.getInstance().build("/app/WXEntryActivity").withString("code",infoBean.getData().getBelongcode()).navigation();
                api = WXAPIFactory.createWXAPI(getActivity(), "wxb0065d1cb10fd744", true);
                api.registerApp("wxb0065d1cb10fd744");

                WXTextObject textObj = new WXTextObject();
                textObj.text = "医疗\n我下在使用医疗APP，新型社区APP，你也来试试吧！邀请码：" + infoBean.getData().getBelongcode();

                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObj;
                msg.description = "医疗\n我下在使用医疗APP，新型社区APP，你也来试试吧！邀请码：" + infoBean.getData().getBelongcode();

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = "text" + System.currentTimeMillis();
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);
            }
        });

        //黑匣子
        view.findViewById(R.id.ll_black_box).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/acitvity/BlackBoxActivity").navigation();
            }
        });
    }

    private IWXAPI api;


    @Override
    public void onStart() {
        super.onStart();
        initNet();
    }

    private void initNet() {

        OkGo.<ResultView>get(UrlApi.doctorGetSingle)
                .tag(this)
                .headers("mbtToken", mbtToken)
                .params("id", SpUtils.getDoctorId(getActivity()))
                .execute(new JsonCallback<ResultView>() {
                    @Override
                    public void onSuccess(Response<ResultView> response) {
                        ResultView resultView = response.body();
                        if (resultView != null) {
                            Map<String, Object> singleBean = (Map<String, Object>) resultView.getData();
                            JSONObject jo = new JSONObject(singleBean);
                            Account account = jo.getObject("account", Account.class);
                            tvAccountMoney.setText(account.getMoney().toString());
                            tvOrderNum.setText(jo.getJSONArray("orderList").size());
                            tvArticleNum.setText(jo.getJSONArray("articleList").size());
                        }
                    }

                    @Override
                    public void onError(Response<ResultView> response) {
                        super.onError(response);
                        Log.i("test", "onError  " + response.body());
                    }
                });


        OkGo.<String>get("http://service.jiangaifen.com:38082/user/getUser")
                .tag(this)
                .headers("mbtToken", mbtToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (!response.body().isEmpty()) {
                            infoBean = JSON.parseObject(response.body(), PersonalInfoBean.class);
                            if (infoBean == null || infoBean.getData() == null) {
                                return;
                            }
                            if (infoBean.getData().getHeadimage() != null) {
                                ImageUtil.loadRoundeImga(getActivity(), infoBean.getData().getHeadimage(), ivHead, 10);
                            }

                            tvName.setText(infoBean.getData().getName());
                            tvPhone.setText("医疗账号：" + infoBean.getData().getPhone());
                            tvInvitaion.setText("好友邀请 (" + infoBean.getData().getBelongcode() + ")");
                            SharedPreferences.Editor editor = sp.edit().putString("belongcode", infoBean.getData().getBelongcode());
                            editor.apply();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.i("test", "onError  " + response.body());
                    }
                });
    }

    private void initView(View view) {
        sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        mbtToken = sp.getString("mbtToken", "");
        view.findViewById(R.id.head_blue_iv_left).setVisibility(View.GONE);
        TextView tvTitle = view.findViewById(R.id.head_blue_tv_center);
        tvTitle.setText("个人中心");
        view.findViewById(R.id.head_blue_iv_right).setVisibility(View.GONE);

        ivHead = view.findViewById(R.id.pf_np_iv_head);
        tvName = view.findViewById(R.id.pf_np_tv_name);
        tvPhone = view.findViewById(R.id.pf_np_tv_username);

        tvInvitaion = view.findViewById(R.id.fnp_monkey_pack_tv_invitation);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
